﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;

namespace devtm.Editor.TypeSelector.Assemblies
{
    
    public class Resolver : IDisposable
    {


        #region Ctor / Dtor

        public Resolver(Hashtable paths)
        {

            this.FilePaths = paths;
            this.Paths = new HashSet<string>();


            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            BuildPaths();

        }         

        public void Dispose(bool disposing)
        {

            if (disposing)
            {

            }

            try
            {
                AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            }
            catch (Exception)
            {

            }
            
        }

        public void Dispose()
        {
            Dispose(true);
        }

        ~Resolver()
        {
            Dispose(false);
        }

        #endregion


        private void BuildPaths()
        {


            var lst = new List<String>();


            foreach (string item in FilePaths.Values)
                lst.Add(item);


            foreach (string item in lst)
            {
                string n = new FileInfo(item).Directory.FullName;
                if (!Paths.Contains(n))
                    Paths.Add(n);
            }

        }      



        System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {

            string n = args.Name;
            if (FilePaths.ContainsKey(n))
            {

                string file = FilePaths[n] as string;

                if (File.Exists(file))
                {
                    System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFile(file);
                    return ass;
                }
            }

            return null;
        }



        public Hashtable FilePaths { get; set; }
        public HashSet<string> Paths { get; set; }


    }
}
